 <!--
 * @Author: zeng_ze
 * @Description: 系统管理 -> 多租户配置
 -->
<template>
  <div class="tenant-container">
    <drawer-layout>
      <template v-slot:left="{ setFolded }">
        <fks-query-page
          v-loading="loading"
          :data="tableData"
          :total="total"
          :page-size.sync="pageSize"
          :current-page.sync="currentPage"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[20, 50, 100]"
          :element-loading-text="LANG.LOADING"
          :table-name="LANG.TENANT_LIST"
          :highlight-current-row="highlight"
          @cell-click="cellClick"
          @sort-change="tenantSortHandler"
          @query="getData"
        >
          <template slot="singleSearch">
            <div class="single-searchBox">
              <fks-button
                v-permission="['tenant:add']"
                type="primary"
                icon="fks-icon-plus"
                @click="add"
              >
                <span> {{ LANG.ADD }}</span>
              </fks-button>
            </div>
          </template>
          <template>
            <fks-table-column type="index" align="center" label="#">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </fks-table-column>
            <fks-table-column prop="tenantId" label="ID" width="120" />
            <fks-table-column
              prop="tenantName"
              :label="LANG.NAME"
              min-width="200"
              align="left"
              sortable="custom"
              is-link
            >
              <span
                slot-scope="scope"
                @click="
                  () => {
                    searchClient(scope)
                    setFolded(true)
                  }
                "
              >
                {{ scope.row.tenantName }}
              </span>
            </fks-table-column>
            <fks-table-column :label="LANG.OPERATION" width="100" align="left">
              <template slot-scope="scope">
                <fks-button
                  v-permission="['tenant:edit']"
                  type="text"
                  @click="editHandle(scope.row)"
                >
                  {{ LANG.EDIT }}
                </fks-button>
                <fks-button
                  v-permission="['tenant:delete']"
                  danger-text
                  @click="deleteHandle(scope.row)"
                >
                  {{ LANG.DELETE }}
                </fks-button>
              </template>
            </fks-table-column>
          </template>
        </fks-query-page>
      </template>
      <template #right>
        <fks-query-page
          v-loading="loadingClient"
          :table-name="tenantNames ? tenantNames : ''"
          :data="list"
          row-key="id"
          :total="totalClient"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :page-size.sync="pageSizeClient"
          :current-page.sync="currentPageClient"
          :element-loading-text="LANG.LOADING"
          @sort-change="sortHandler"
        >
          <template slot="singleSearch">
            <div class="single-searchBox">
              <fks-button
                v-permission="['tenantClient:add']"
                type="primary"
                icon="fks-icon-plus"
                @click="addClient"
              >
                <span> {{ LANG.ADD }}</span>
              </fks-button>
            </div>
          </template>
          <template>
            <fks-table-column type="index" align="center" label="#">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </fks-table-column>
            <fks-table-column
              :label="LANG.NAME"
              prop="clientName"
              align="left"
              min-width="120"
              sortable="custom"
              header-align="center"
            />
            <fks-table-column
              :label="LANG.REDIRECT_URL"
              prop="webServerRedirectUri"
              align="left"
              min-width="200"
              header-align="center"
            />
            <fks-table-column
              :label="LANG.CLIENT_ID"
              prop="clientId"
              align="left"
              min-width="120"
              header-align="center"
            />
            <fks-table-column :label="LANG.OPERATION" width="100" align="left">
              <template slot-scope="scope">
                <fks-button
                  v-permission="['tenantClient:edit']"
                  type="text"
                  @click="edit(scope.row)"
                >
                  {{ LANG.EDIT }}
                </fks-button>
                <fks-button
                  v-permission="['tenantClient:delete']"
                  danger-text
                  @click="deleteClient(scope.row)"
                >
                  {{ LANG.DELETE }}
                </fks-button>
              </template>
            </fks-table-column>
          </template>
        </fks-query-page>
      </template>
    </drawer-layout>
    <template v-if="addEditVisible">
      <!-- 新增&&编辑租户 同一个表单 -->
      <fks-dialog
        :visible="true"
        :append-to-body="true"
        width="480px"
        :title="title"
        @close="close"
      >
        <div slot="title">
          <i v-if="title == LANG.ADD" class="fks-icon-plus" />
          <i v-if="title == LANG.EDIT" class="fks-icon-edit" />
          {{ title }}
        </div>
        <fks-form
          ref="Form"
          :model="Form"
          :rules="rules"
          status-icon
          label-width="85px"
        >
          <fks-form-item
            :span="24"
            lead
            :label="LANG.TENANT_NAME"
            prop="tenantName"
          >
            <fks-input
              v-model="Form.tenantName"
              maxlength="50"
              show-word-limit
            />
          </fks-form-item>
          <fks-form-item
            v-if="title == LANG.ADD"
            :span="24"
            lead
            :label="LANG.INIT"
            prop="initTenantData"
          >
            <span slot="label">
              <span style="margin-right: 4px">{{ LANG.INIT }}</span>
              <fks-tooltip>
                <div
                  slot="content"
                  style="font-size: 14px; line-height: 20px"
                  class="tips-container"
                >
                  {{ LANG.INIT_TIP }}
                </div>
                <i class="fks-icon-question" />
              </fks-tooltip>
            </span>
            <fks-switch v-model="Form.initTenantData" />
          </fks-form-item>

          <!-- <fks-form-item
                :label="LANG.TENANTORGANIZATION"
                :span="12"
                prop="orgNo"
              >
                <fks-org-selector
                  urlPath="/sys-user/orgs/tree"
                  :deptId.sync="Form.orgNo"
                  :deptName.sync="Form.orgName"
                  multiple
                ></fks-org-selector>
              </fks-form-item> -->
        </fks-form>
        <template slot="footer">
          <fks-button
            type="primary"
            :loading="tenantLoading"
            icon="fks-icon-check"
            @click="save"
          >
            <span style="margin-left: 4px">{{ LANG.SAVE }}</span>
          </fks-button>
        </template>
      </fks-dialog>
    </template>
    <client-info
      v-if="clientVisible"
      :type="clientTitle"
      :data="clientData"
      :visible.sync="clientVisible"
    />
  </div>
</template>
<script>
import Mix from '@/mixins/module'
import ClientInfo from './ClientInfo'
import DrawerLayout from '@/components/DrawerLayout'

import * as Tenant from './api'
export default {
  name: 'Tenant',
  components: { ClientInfo, DrawerLayout },
  mixins: [Mix],
  data() {
    return {
      type: 'add',
      visible: false,
      node: {},
      list: [],
      clientTitle: '',
      clientData: {},
      clientVisible: false,
      show: false,
      currentPage: 1,
      currentPageClient: 1,
      tenantLoading: false,
      total: 0,
      tenantId: '',
      totalClient: 0,
      highlight: false,
      pageSize: 20,
      pageSizeClient: 20,
      tenantNames: '',
      size: '',
      sort: '',
      sortColumn: '',
      tableData: [],
      loading: false,
      loadingClient: false,
      addEditVisible: false,
      title: '',
      clientColumnName: '',
      clientSort: '',
      Form: {
        tenantName: '',
        orgNo: '',
        orgName: '',
        initTenantData: false
      },
      form: {}
    }
  },
  computed: {
    //验证规则
    rules() {
      return {
        tenantName: [
          {
            required: true,
            message: this.LANG.TENANT_NOT_EMPTY,
            trigger: 'blur'
          }
        ],
        tenantId: [
          {
            required: true,
            message: this.LANG.TENANT_NOT_EMPTY,
            trigger: 'change'
          }
        ],
        orgNo: [
          {
            required: true,
            message: this.LANG.TENANT_NOT_EMPTY,
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    tenantNames(val) {
      if (val.length > 20) {
        this.tenantNames = val.slice(0, 20) + '...'
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    //租户列表排序
    tenantSortHandler(data) {
      let params = {}
      if (!data.order) {
        this.sort = ''
        this.columnName = ''
      } else {
        this.sort = data.order == 'ascending' ? 'asc' : 'desc'
        this.columnName = 'tenant_name'
      }
      params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        sort: this.sort,
        columnName: this.columnName
      }
      this.getTenantList(params)
    },
    //应用列表排序
    sortHandler(data) {
      let params = {}
      if (!data.order) {
        this.clientSort = ''
        this.clientColumnName = ''
      } else {
        this.clientSort = data.order == 'ascending' ? 'asc' : 'desc'
        this.clientColumnName = 'client_name'
      }
      params = {
        pageNo: this.currentPageClient,
        pageSize: this.pageSizeClient,
        tenantId: this.tenantId,
        sort: this.clientSort,
        columnName: this.clientColumnName
      }
      this.getClientList(params)
    },
    //获取对应租户下的应用
    searchClient({ row }) {
      this.tenantId = row.tenantId
      this.form.tenantId = row.tenantId
      this.highlight = true
      this.tenantNames = row.tenantName
      this.getClients()
    },
    //表格点击回调
    cellClick() {
      this.highlight = false
    },
    //打开新增应用弹窗
    addClient() {
      this.clientTitle = 'add'
      this.clientVisible = true
      this.clientData = { tenantId: this.tenantId }
    },
    //关闭租户弹窗
    close() {
      this.addEditVisible = false
      this.show = false
    },
    //打开编辑应用弹窗
    edit(val) {
      this.clientData = {
        clientId: val.clientId,
        clientName: val.clientName,
        clientSecret: val.clientSecret,
        webServerRedirectUri: val.webServerRedirectUri,
        id: val.id,
        tenantId: val.tenantId
      }
      this.clientTitle = 'edit'
      this.clientVisible = true
    },
    //删除应用
    deleteClient(row) {
      this.$confirm(this.LANG.DELETE_CONFIRM, {
        title: this.LANG.TIPS,
        type: 'warning',
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true
      })
        .then(() => {
          Tenant.deleteClient(row.id)
            .then((res) => {
              if (res.status) {
                this.$message.success(this.LANG.DELETE_SUCCESS)
                this.getClients()
                this.getData()
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    //获取租户分页
    getData() {
      this.loading = true
      this.loadingClient = true
      let params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        sort: this.sort,
        columnName: this.columnName
      }
      this.getTenantList(params)
    },
    //获取租户列表数据并获取第一个租户下应用数据
    getTenantList(data) {
      Tenant.getTenant(data)
        .then((res) => {
          this.loading = false
          if (res.status) {
            this.size = res.data.size
            this.total = res.data.total
            this.tableData = res.data.list
            this.highlight = true
            this.list = []
            if (res.data.list[0]) {
              this.tenantNames = res.data.list[0].tenantName
              this.tenantId = res.data.list[0].tenantId
              Tenant.getClients({
                tenantId: this.tenantId,
                pageNo: this.currentPageClient,
                pageSize: this.pageSizeClient
              })
                .then((res) => {
                  this.loadingClient = false
                  if (res.data && res.data.list) {
                    this.totalClient = res.data.total
                    this.list = res.data.list
                  }
                })
                .catch((error) => {
                  this.loadingClient = false
                })
            } else {
              this.totalClient = 0
              this.loadingClient = false
              this.list = []
              this.tenantNames = ''
            }
          } else {
            this.loadingClient = false
          }
        })
        .catch((err) => {
          this.loading = false
          this.loadingClient = false
        })
    },
    //获取应用列表数据
    getClients() {
      this.list = []
      this.loadingClient = true
      let params = {
        tenantId: this.tenantId,
        pageNo: this.currentPageClient,
        pageSize: this.pageSizeClient,
        sort: this.clientSort,
        columnName: this.clientColumnName
      }
      this.getClientList(params)
    },
    //获取应用列表数据
    getClientList(data) {
      Tenant.getClients(data)
        .then((res) => {
          this.highlight = true
          if (res.data && res.data.list) {
            this.totalClient = res.data.total
            this.list = res.data.list
          }
          this.loadingClient = false
        })
        .catch((error) => {
          this.loadingClient = false
        })
    },
    //根据id删除租户
    deleteHandle(row) {
      this.$confirm(this.LANG.DELETE_CONFIRM, {
        title: this.LANG.TIPS,
        type: 'warning',
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true
      })
        .then(() => {
          Tenant.deleteTenant(row.id)
            .then((res) => {
              if (res.status) {
                this.$message.success(this.LANG.DELETE_SUCCESS)
                if (this.size == '1') {
                  this.currentPage = 1
                }
                this.getData()
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    //打开新增租户弹窗
    add() {
      this.title = this.LANG.ADD
      this.Form = {
        tenantName: '',
        orgName: '',
        orgNo: ''
      }
      this.addEditVisible = true
    },
    //打开编辑租户弹窗
    editHandle(row) {
      this.title = this.LANG.EDIT
      this.Form = JSON.parse(JSON.stringify(row))
      this.addEditVisible = true
    },
    //保存租户数据
    save() {
      this.$refs.Form.validate((valid) => {
        if (valid) {
          this.tenantLoading = true
          if (this.title == this.LANG.ADD) {
            if (!this.Form.initTenantData) {
              this.Form.initTenantData = false
            }
            Tenant.addTenant(JSON.stringify(this.Form))
              .then((res) => {
                this.tenantLoading = false
                if (res.status) {
                  this.$message.success(this.LANG.ADD_SUCCESS)
                  this.addEditVisible = false
                  this.getData()
                }
              })
              .catch((error) => {
                this.tenantLoading = false
              })
          } else {
            Tenant.editTenant(this.Form)
              .then((res) => {
                this.tenantLoading = false
                if (res.status) {
                  this.$message.success(this.LANG.EDIT_SUCCESS)
                  this.addEditVisible = false
                  this.getData()
                }
              })
              .catch((error) => {
                this.tenantLoading = false
              })
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.tenant-container {
  min-width: 632px;
}

::v-deep .fks-dialog__body {
  padding-bottom: 0;
}
</style>